package com.anran.netty.client;


import com.anran.netty.message.*;
import com.anran.netty.protocol.MessageCodecSharable;
import com.anran.netty.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {


    public static void main(String[] args) {

        NioEventLoopGroup group = new NioEventLoopGroup();

        //协议
        MessageCodecSharable MESSAGE = new MessageCodecSharable();
        //日志
        LoggingHandler LOG = new LoggingHandler(LogLevel.DEBUG);
        //倒计时锁
        CountDownLatch wait_Login_Lock = new CountDownLatch(1);
        //
        AtomicBoolean login = new AtomicBoolean(false);


        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    //ch.pipeline().addLast(LOG);
                    ch.pipeline().addLast(MESSAGE);
                    ch.pipeline().addLast(new IdleStateHandler(0,3,0));
                    //即为入站处理器、也为出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        //用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            //读空闲
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug("写空闲已经超过3秒");
                                ctx.writeAndFlush(new PingMessage());
                            }
                            super.userEventTriggered(ctx, evt);
                        }
                    });

                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                            if((msg instanceof LoginResponseMessage)    ) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                if(response.isSuccess()) {
                                    //登陆成功
                                    login.set(true);
                                }
                                //唤醒system in线程
                                wait_Login_Lock.countDown();
                            }
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {

                            new Thread(()->{
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码");
                                String password = scanner.nextLine();

                                LoginRequestMessage message = new LoginRequestMessage(username,password);

                                ctx.writeAndFlush(message);
                                System.out.println("请等待");
                                //
                                try {
                                    wait_Login_Lock.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                //如果登陆失败
                                if (!login.get()) {
                                    ctx.channel().close();
                                    return;
                                }

                                while (true) {
                                    System.out.println("============ 功能菜单 ============");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String command = scanner.nextLine();
                                    String[] s = command.split(" ");

                                    switch (s[0]){
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gcreate":
                                            Set<String> groupNameList = new HashSet<>(Arrays.asList(s[2].split(",")));
                                            groupNameList.add(username);
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], groupNameList));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username,s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username,s[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }


                                }

                            },"system in").start();

                        }
                    });

                }


            });

            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();

            // ... 这个位置 ： 连接已经建立好了  【可以写 登录 ， 也可以在 channelActive(连接建立后触发此事件) 里写】

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Client error", e);
        } finally {

            group.shutdownGracefully();

        }

    }


}
